package com.glodon.utils.service;

import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

@Service
public class StringRedisService {

	/**
	 * 日志管理
	 */
	private Logger logger = LoggerFactory.getLogger(StringRedisService.class);

	/**
	 * Redis String操作模板
	 */
	@Autowired(required = false)
	private StringRedisTemplate stringRedisTemplate;

	/**
	 * 构造方法
	 */
	public StringRedisService() {
		logger.info("[StringRedisService实例化，被Spring管理]");
	}

	/**
	 * @param keys
	 * @throws Exception
	 */
	public void deleteByKey(String ... keys) throws Exception{
		try {
			for (String key : keys) {
				stringRedisTemplate.delete(key);
			}
		} catch (Exception e) {
			throw new Exception();
		}
	}
	
	/**
	 * 缓存变量，并制定过期时间
	 * 
	 * @param key
	 *            变量的Key
	 * @param value
	 *            变量的值
	 * @param expire
	 *            过期时间周期，单位分钟
	 * @throws Exception
	 */
	public void setExpire(String key, String value, int expire) throws Exception {
		try {
			stringRedisTemplate.delete(key);
			stringRedisTemplate.opsForValue().set(key, value);
			stringRedisTemplate.expire(key, expire, TimeUnit.MINUTES);
		} catch (Exception e) {
			throw new Exception();
		}
	}

	/**
	 * 缓存变量
	 * 
	 * @param key
	 *            变量的Key
	 * @param value
	 *            变量的值
	 * @throws Exception
	 */
	public void set(String key, String value) throws Exception {
		try {
			stringRedisTemplate.opsForValue().set(key, value);
		} catch (Exception e) {
			throw new Exception();
		}
	}

	/**
	 * 获取
	 * 
	 * @param key
	 * @return
	 * @throws Exception
	 */
	public String get(String key) throws Exception {
		String result = "";
		try {
			result = stringRedisTemplate.opsForValue().get(key);
		} catch (Exception e) {
			throw new Exception();
		}
		return result;
	}
}
